package lmycc.test.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lmycc.test.demo.domain.Email;
import lmycc.test.demo.domain.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@Component
@Transactional
public class EmailController {
    Map message = new HashMap();
    ObjectMapper mapper = new ObjectMapper();
    Object entiy = null;
    @Autowired
    private JavaMailSender mailSender; //框架自带的
    private String sendFrom = "13932460374@163.com";

    @RequestMapping("/sendEmail")
    @ResponseBody
    public Map sendSimpleMail(@RequestBody String string) {
        //@RequestParam(value = "file", required = true) MultipartFile file,
        //String filePath = file.getOriginalFilename(); // 获取文件的名称
        //filePath = "F:\\Pic1\\" + filePath;   // 这是文件的保存路径，如果不设置就会保存到项目的根目录
        //System.out.println(filePath + "..." + file.getName());
        try {
            entiy = mapper.readValue(string, Email.class);
            Email e_mail = (Email) entiy;
            MimeMessage mailMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = null; //开启带附件true
            messageHelper = new MimeMessageHelper(mailMessage, true);
            messageHelper.setFrom(sendFrom);                              //发送者
            messageHelper.setTo(e_mail.getConsignee());                   //接收者
            messageHelper.setSubject(e_mail.getProject());                //发送的标题
            messageHelper.setText(e_mail.getContent());                   //发送的内容
            // FileSystemResource filePath = new FileSystemResource(new File("F:\\q.jpg")); //选择文件
            // messageHelper.addAttachment("图片.jpg", filePath);//加入邮件
            mailSender.send(mailMessage);
            message.put("message", "success");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message;
    }
}
